package ihm.panel.info;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;	

import ihm.applet.KrakenApplet;
import ihm.panel.TablePanel;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import tools.AppletConstant;

import enumTypes.LogType;

import bdd.sql.server.bean.Log;
import bdd.sql.server.bean.User;
import bdd.sql.server.bean.User_Log;

/**
 * Affiche les alertes.
 * @author Guillaume Pocas & Jean-Fraçois Augé
 */
public class AlertPanel extends TablePanel implements ActionListener  {
	
	private static final long serialVersionUID = 1L;
	private KrakenApplet applet;
	
	private DefaultTableModel model;
	private JTable table;
	private static String[] COLUMN_NAMES = {"Date", "Type", "Machine", "Application", "Message", "Lue"};
										 //{"ID", "Date", "Source", "Message", "Lu"};
	
	private JPanel bottom_jp;
	private JButton read_jb;
	
	/**
	 * Constructeur.
	 * @param applet
	 */
	public AlertPanel(KrakenApplet applet) {
		this.applet = applet;
		setLayout(new BorderLayout());

		// Table part!
		model = new DefaultTableModel(populateModel(), COLUMN_NAMES);
		model.addTableModelListener(this);

		table = new JTable(model) {
			private static final long serialVersionUID = 1L;

			//  Returning the Class of each column will allow different
			//  renderers to be used based on Class
			@SuppressWarnings({ "unchecked", "rawtypes" })
			public Class getColumnClass(int column) {
				return getValueAt(0, column).getClass();
			}

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		table.setPreferredScrollableViewportSize(table.getPreferredSize());
		table.setFillsViewportHeight(true);

		TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
		table.setRowSorter(sorter);

		JScrollPane scrollPane = new JScrollPane(table);
		add(scrollPane, BorderLayout.CENTER);
		
		// Buttons part!
		bottom_jp = new JPanel();

		read_jb = new JButton("Lire");
		read_jb.addActionListener(this);
		read_jb.setPreferredSize(AppletConstant.BUTTON_SIZE);
		bottom_jp.add(read_jb);
		add(bottom_jp, BorderLayout.SOUTH);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		int row = table.getSelectedRow();
		
		Object[] options = {"Marquer comme lu", "Marquer comme non lu"};
		int res = JOptionPane.showOptionDialog(this,
				table.getValueAt(row, 3),
				"Alerte de "+table.getValueAt(row, 2),
				JOptionPane.YES_NO_OPTION,
			    JOptionPane.INFORMATION_MESSAGE,
			    null,
			    options,
			    options[0]);

		Session session = applet.getSession();
		
		Log l = (Log) table.getValueAt(row, 4);
		User u = (User) session.load(User.class, applet.getUser_ID());
		
		@SuppressWarnings("unchecked")
		List<User_Log> alerts = session.createCriteria(User_Log.class)
				.add(Restrictions.eq("user.id", u.getUser_id()))
				.add(Restrictions.eq("log.id", l.getLog_id()))
				.list();
		
		User_Log alert = null;
		if(alerts.size() > 0) // si l'alerte est déjà dans la base, on va la chercher
			alert = alerts.get(0);
		else // sinon on en créer une nouvelle
			alert = new User_Log(u, l);
		
		Transaction tx = session.beginTransaction();
		
		if(res==0) {
			model.setValueAt(true, table.convertRowIndexToModel(row), 5);
			//alert.setUser_log_read(true);
			alert.setUser_log_read(1);
		}
		else {
			model.setValueAt(false, table.convertRowIndexToModel(row), 5);
			//alert.setUser_log_read(false);
			alert.setUser_log_read(0);
		}
		
		session.save(alert);
		tx.commit();
		
		session.close();
	}

	@Override
	public Object[][] populateModel() {
		if(applet.isUserLogged()){
			int i = 0;

			Session session = applet.getSession();
			User user = (User) session.load(User.class, applet.getUser_ID());
			
			@SuppressWarnings("unchecked")
			List<Log> resultats = session.createCriteria(Log.class).add(Restrictions.eq("log_type_importance", LogType.Alert)).addOrder(Order.desc("id")).list();
			Object[][] data = new Object[resultats.size()][COLUMN_NAMES.length];
			
			for(Log log : resultats) {
				@SuppressWarnings("unchecked")
				List<User_Log> alerts = session.createCriteria(User_Log.class)
						.add(Restrictions.eq("user.id", user.getUser_id()))
						.add(Restrictions.eq("log.id", log.getLog_id()))
						.list();
				
				data[i][0] = log.getLog_date();
				//data[i][1] = log.getLog_type();
				//data[i][2] = log.getLog_machine();
				//data[i][3] = log.getLog_app();
				data[i][1] = log.getLog_type_importance();
				data[i][2] = log.getLog_type_equipement();
				data[i][3] = "";
				data[i][4] = log;
				
				if(alerts.size() != 0) // si l'alerte existe dans la base, on affiche si elle est lue ou non
					if(alerts.get(0).isUser_log_read() == 1)
						data[i][5] = true;
					else
						data[i][5] = false;
				else // sinon elle n'est pas lue par défaut
					data[i][5] = false;
				
				i++;
			}
			session.close();
	
			return data;
		}
		else
			return null;
	}

	@Override
	public void updateTableInfo() {
		setLocked(true);
		model.setDataVector(populateModel(), COLUMN_NAMES);
		setLocked(false);
	}

	@Deprecated
	public void tableChanged(TableModelEvent e) {
		//ne doit pas arriver ici...
	}
	
}
